package com.huluobo.a2303mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.google.gson.Gson
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/9/4.
 */
//封装联系人的Bean
//用户名,首字符,是否显示首字符
data class ContactEntity(val username: String, val firstLetter: Char, val isShowFirstLetter: Boolean)

@Composable
fun ContactPage(navHostController: NavHostController) {
    val list = remember {
        SnapshotStateList<ContactEntity>()
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            //同步特点就是排队,如果代码执行到同步方法的时候,会线程卡死,当它没有产生返回值的时候,当前线程会一直进行等待
            //异步特点就是同时进行,开启新线程来获取数据,执行的快慢不一定,当异步方法进行请求的时候,数据可能还没有返回,代码就已经执行完毕
            //同步方法
//            EMClient.getInstance().contactManager().allContactsFromServer
            EMClient.getInstance().contactManager()
                .aysncGetAllContactsFromServer(object : EMValueCallBack<List<String>> {
                    override fun onSuccess(value: List<String>?) {
                        if (!value.isNullOrEmpty()) {
                            val sortedBy = value.sortedBy { it.first() }

//                            for (i in sortedBy) {
//                                list.add(ContactEntity(i, i.first().toUpperCase(), true))
//                            }

                            for ((index, item) in sortedBy.withIndex()) {
                                var isShow = false
                                //判断何时显示首字符
                                //首先第一个item肯定显示
                                //从第二个开始需要对比item之间首字符是否相等
                                if (index == 0 || sortedBy[index].first() != sortedBy[index - 1].first()) {
                                    isShow = true
                                }
                                list.add(ContactEntity(item, item.first().toUpperCase(), isShow))
                            }

                        }
                    }

                    override fun onError(error: Int, errorMsg: String?) {
                    }
                })
        }
    })

    Column(Modifier.padding(20.dp)) {
        BaseTitle(title = "联系人", navHostController = navHostController)
        Spacer(modifier = Modifier.height(20.dp))
        LazyColumn(content = {
            items(list) {
                ContactItem(entity = it, navHostController = navHostController)
            }

        }, verticalArrangement = Arrangement.spacedBy(10.dp))
    }
}

@Composable
fun ContactItem(entity: ContactEntity, navHostController: NavHostController) {
    Column(Modifier.padding(5.dp)) {
        if (entity.isShowFirstLetter) {
            Text(
                text = "${entity.firstLetter}",
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .background(color = Color.LightGray)
                    .padding(start = 5.dp)
                    .fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(10.dp))
        }
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(20.dp),
            modifier = Modifier
                .clickable {
                    val chatBean = ChatBean(entity.username, EMMessage.ChatType.Chat)
                    val json = Gson().toJson(chatBean)
                    navHostController.navigate(RoutePath.CHAT + "/$json")
                }
                .fillMaxWidth()
        ) {
            AsyncImage(
                model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                contentDescription = "",
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(5.dp)),
                contentScale = ContentScale.Crop
            )
            Text(text = entity.username)
        }
        Spacer(modifier = Modifier.height(10.dp))
        Divider(color = Color.LightGray, thickness = 0.5.dp)
    }
}